import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import { useLocation } from 'react-router-dom'

const diffClassName = pathname => current => pathname === current ? 'nav-link active' : 'nav-link'

const LoggeIn = function ({ user }) {
  const { token, username, image } = user
  const { pathname } = useLocation()
  const toggleClassName = diffClassName(pathname)
  if (token) {
    return (
      <ul className="nav navbar-nav pull-xs-right">
        <li className="nav-item">
          <Link to="/" className={toggleClassName('/')}>
            Home
          </Link>
        </li>

        <li className="nav-item">
          <Link to="/editor" className={toggleClassName('/editor')}>
            <i className="ion-compose"></i>&nbsp;New Post
          </Link>
        </li>

        <li className="nav-item">
          <Link to="/settings" className={toggleClassName('/settings')}>
            <i className="ion-gear-a"></i>&nbsp;Settings
          </Link>
        </li>

        <li className="nav-item">
          <Link
            to={`/@${username}`}
            className={toggleClassName(`/@${username}`)}>
            <img
              src={image || 'https://static.productionready.io/images/smiley-cyrus.jpg'}
              className="user-pic"
              alt={username} />
            {username}
          </Link>
        </li>
      </ul>
    )
  }
  return null
}

const LoggeOut = function ({ user }) {
  const { pathname } = useLocation()
  const toggleClassName = diffClassName(pathname)
  const { token } = user
  if (!token) {
    return (
      <ul className="nav navbar-nav pull-xs-right">
        <li className="nav-item">
          <Link to="/" className={toggleClassName('/')}>Home</Link>
        </li>
        <li className="nav-item">
          <Link to="/login" className={toggleClassName('/login')}>Sign in</Link>
        </li>
        <li className="nav-item">
          <Link to="/register" className={toggleClassName('/register')}>Sign up</Link>
        </li>
      </ul>
    )
  }
  return null
}



function Header(props) {
  const { user } = props
  return (
    <nav className="navbar navbar-light">
      <div className="container">
        <Link className="navbar-brand" to="/">conduit</Link>
        <LoggeIn user={user} />
        <LoggeOut user={user}  />
      </div>
    </nav >
  )
}

const mapStateToProps = state => ({
  user: state.user.user || {}
})


export default connect(mapStateToProps, null)(Header)